const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const router = new Router();
// 购物车一个商户的
router.post('/app/saveBf', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId
    let uid = user.id
    let buId = ctx.request.body.buId
    let buName = ctx.request.body.buName
    let bfContent = ctx.request.body.bfContent
    let pics = ctx.request.body.pics
    let bf = {
        tenantId,
        buId,
        salesId: uid,
        arrived: tool.getTime(),
        state: '已完成',
        bfContent,
        billDate: tool.getDay(),
        cby: uid,
        ctime: tool.getTime(),
    }
    let bfPics = []

    if(buId) {
        let model = await db.models['contactBf'].create(bf)
        if(model.id) {
            await  db.models['contactBfPic'].destroy({
                where: {
                    contactBfId: model.id,
                }
            })
            if(pics.length > 0) {
                for (let i = 0; i < pics.length; i++) {
                    bfPics.push({
                        tenantId,
                        fileName: pics[i],
                        contactBfId: model.id,
                    })
                }
                await db.models['contactBfPic'].bulkCreate(bfPics)
            }
            return  ctx.suc('保存成功', model)
        }
        else {
            return ctx.err('保存失败')
        }
    }
    else {
        return ctx.err('请选择终端')
    }

})
// 拜访记录
router.post('/app/bfList', async ctx => {
    let tenantId= ctx.user.tenantId
    let uid= ctx.user.id
    let body= ctx.request.body
    let currentPage= body.currentPage
    let keyWord= body.keyWord?body.keyWord:''
    let pageSize= body.pageSize?body.pageSize:30
    let offset = (currentPage - 1) * pageSize;

    let sql = `select a.*,b.name buName from contact_bf a inner join contact b on a.buId=b.id 
                       where a.tenantId=${tenantId} and a.salesId=${uid}  `
    if(keyWord) {
        sql += ` and(b.name like '%${keyWord}%'  ) `
    }
    let total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
    let list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
    return ctx.suc('', {
        total: total.total,
        list
    })
})
router.post('/app/bfDetail', async ctx => {
    let tenantId= ctx.user.tenantId
    let id= ctx.request.body.id
    let pics = await db.models['contactBfPic'].findAll({
        where: {
            tenantId,
            contactBfId: id
        }
    })
    let model = await db.query(`select a.*,b.name buName from contact_bf a inner join contact b on a.buId=b.id 
where a.id=${id} `,{type: QueryTypes.SELECT, plain: true})
    return ctx.suc('', {bf: model, pics})

})

module.exports = router;
